package com.tybbank.Activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nanchen.compresshelper.CompressHelper;
import com.tybbank.Base.BaseActivity;
import com.tybbank.Bean.VerifiedBean;
import com.tybbank.Bean.YZMBean;
import com.tybbank.Bean.imagebenan;
import com.tybbank.MyApplication;
import com.tybbank.R;
import com.tybbank.Utils.Constant;
import com.tybbank.Utils.MD5Utils;
import com.tybbank.Utils.MyDialogUtils;
import com.tybbank.Utils.logUtilssss;
import com.yuyh.library.imgsel.ImageLoader;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.ImgSelConfig;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.Comparator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class ToVerifiedActivity extends BaseActivity {

    private static final String TAG = "ToVerifiedActivity";
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_real_name)
    EditText etRealName;
    @BindView(R.id.et_id_card)
    EditText etIdCard;
    @BindView(R.id.iv_add_card_front)
    ImageView ivAddCardFront;
    @BindView(R.id.rl_pingzheng)
    RelativeLayout rlPingzheng;
    @BindView(R.id.iv_add_card_reverse)
    ImageView ivAddCardReverse;
    @BindView(R.id.exit_enter)
    Button exitEnter;
    @BindView(R.id.iv_add_with_hand)
    ImageView ivAddWithHand;
    private File frontFile;//身份证正面图片
    private File reverseFile;//身份证反面图片
    private File withHandFile;//手持身份证图片
    private String frontImageUrl;//身份证正面图片图片地址
    private String reverseImageUrl;//身份证反面图片图片地址
    private String withHandUrl;//手持身份证照片地址
    private String imageurlone = "";
    private String imageurltwo = "";
    private String imageurlthere = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_to_verified);
        ButterKnife.bind(this);
        toolbar(toolbar, getString(R.string.shimingrenzheng), R.mipmap.icon_close);
        try {
            if ("1".equals(getIntent().getStringExtra("type"))) {
                VerifiedBean.DataBean data = (VerifiedBean.DataBean) getIntent().getSerializableExtra("bean");
                exitEnter.setVisibility(View.GONE);
                ivAddCardFront.setEnabled(false);
                ivAddCardReverse.setEnabled(false);
                ivAddWithHand.setEnabled(false);
                etIdCard.setEnabled(false);
                etRealName.setEnabled(false);
                etRealName.setText(data.getName());
                etIdCard.setText(data.getIdcard());
                Glide.with(this).load(data.getJust_card()).into(ivAddCardFront);
                Glide.with(this).load(data.getBack_card()).into(ivAddCardReverse);
                Glide.with(this).load(data.getHandheld_front()).into(ivAddWithHand);

            }
        } catch (Exception e) {

        }


    }

    @Override
    public void LeftClose() {
        super.LeftClose();
        ToVerifiedActivity.this.finish();
    }

    @OnClick({R.id.exit_enter, R.id.iv_add_card_front, R.id.iv_add_card_reverse, R.id.iv_add_with_hand})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_add_card_front:
                selectPhoto(101);
                break;
            case R.id.iv_add_with_hand:
                selectPhoto(303);
                break;
            case R.id.iv_add_card_reverse:
                selectPhoto(202);
                break;
            case R.id.exit_enter:
                if (TextUtils.isEmpty(etRealName.getText().toString())) {
                    showTips(getString(R.string.name));
                } else if (TextUtils.isEmpty(etRealName.getText().toString())) {
                    showTips(getString(R.string.shenfenzhenghao));
                } else {
                    submitPay();
                }
                break;
        }
    }

    //提交资料
    private void submitPay() {
        if (TextUtils.isEmpty(imageurlone) || TextUtils.isEmpty(imageurltwo)|| TextUtils.isEmpty(imageurlthere)) {
            Toast.makeText(getBaseContext(), getString(R.string.zhengfanmian), Toast.LENGTH_SHORT).show();
            return;
        } else {
            String time = MD5Utils.getTime();
            SortedMap<String, String> parameters = new TreeMap<String, String>(
                    new Comparator<String>() {
                        public int compare(String obj1, String obj2) {
                            // 降序排序
                            return obj1.compareTo(obj2);
                        }
                    });
            parameters.put("uuid", MyApplication.uuid);
            parameters.put("token", MyApplication.token);
            parameters.put("just_card", imageurlone);
            parameters.put("back_card", imageurltwo);
            parameters.put("handheld_front", imageurlthere);
            parameters.put("name", etRealName.getText().toString().trim());
            parameters.put("idcard", etIdCard.getText().toString().trim());
            parameters.put("TimeStamp", time);
            String sign = MD5Utils.createSign(parameters);
            final Dialog dialog = MyDialogUtils.createLoadingDialog(this, "正在加载...");
            dialog.show();
            OkHttpUtils.post()
                    .url(Constant.add_user_auth)
                    .addParams("uuid", MyApplication.uuid)
                    .addParams("token", MyApplication.token)
                    .addParams("TimeStamp", time)
                    .addParams("Sign", sign)
                    .addParams("just_card", imageurlone)
                    .addParams("back_card", imageurltwo)
                    .addParams("handheld_front", imageurlthere)
                    .addParams("name", etRealName.getText().toString().trim())
                    .addParams("idcard", etIdCard.getText().toString().trim())
                    .build()
                    .readTimeOut(30000)
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            dialog.dismiss();
                            Toast.makeText(getBaseContext(), getString(R.string.error), Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            dialog.dismiss();
                            logUtilssss.e("TAG上传图片结果" + response);
                            try {
                                YZMBean enterBean = new Gson().fromJson(response, new TypeToken<YZMBean>() {
                                }.getType());
                                int status = enterBean.getCode();
                                if (status == 1011) {
                                    Toast.makeText(getBaseContext(), enterBean.getMsg(), Toast.LENGTH_SHORT).show();
                                    setResult(RESULT_OK);
                                    finish();
                                } else {
                                    Toast.makeText(getBaseContext(), enterBean.getMsg(), Toast.LENGTH_SHORT).show();
                                }

                            } catch (Exception e) {

                            }

                        }
                    });
        }

    }


    //选择图片
    private void selectPhoto(int requestCode) {
        // 自定义图片加载器
        ImageLoader loader = new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                // TODO 在这边可以自定义图片加载库来加载ImageView，例如Glide、Picasso、ImageLoader等
                Glide.with(context).load(path).into(imageView);
            }
        };
        // 自由配置选项
        ImgSelConfig config = new ImgSelConfig.Builder(ToVerifiedActivity.this, loader)
                // 是否多选, 默认true
                .multiSelect(false)
                // 是否记住上次选中记录, 仅当multiSelect为true的时候配置，默认为true
                .rememberSelected(false)
                // “确定”按钮背景色
                .btnBgColor(Color.GRAY)
                // “确定”按钮文字颜色
                .btnTextColor(Color.BLUE)
                // 使用沉浸式状态栏
                .statusBarColor(Color.parseColor("#3F51B5"))
                // 返回图标ResId
                .backResId(R.mipmap.icon_close)
                // 标题
                .title("图片")
                // 标题文字颜色
                .titleColor(Color.WHITE)
                // TitleBar背景色
                .titleBgColor(Color.parseColor("#3F51B5"))
                // 裁剪大小。needCrop为true的时候配置
//                .cropSize(1, 1, 200, 200)
                .needCrop(false)
                // 第一个是否显示相机，默认true
                .needCamera(true)
                // 最大选择图片数量，默认9
                .maxNum(1).build();
        // 跳转到图片选择器
        ImgSelActivity.startActivity(this, config, requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 101) {
            if (resultCode == RESULT_OK && data != null) {
                List<String> pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
                //新的功能，上传前压缩图片 2018.05.29版本5
                frontFile = CompressHelper.getDefault(this).compressToFile(new File(pathList.get(0)));
                frontImageUrl = pathList.get(0);
                imagepath(this, frontImageUrl, frontFile, ivAddCardFront, "1");


            }
        } else if (requestCode == 202) {
            if (resultCode == RESULT_OK && data != null) {
                List<String> pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
                //新的功能，上传前压缩图片 2018.05.29版本5
                reverseFile = CompressHelper.getDefault(this).compressToFile(new File(pathList.get(0)));
                reverseImageUrl = pathList.get(0);
                imagepath(this, reverseImageUrl, reverseFile, ivAddCardReverse, "2");
            }
        }else if (requestCode == 303) {
            if (resultCode == RESULT_OK && data != null) {
                List<String> pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);
                //新的功能，上传前压缩图片 2018.05.29版本5
                withHandFile = CompressHelper.getDefault(this).compressToFile(new File(pathList.get(0)));
                withHandUrl = pathList.get(0);
                imagepath(this, withHandUrl, withHandFile, ivAddWithHand, "3");
            }
        }

    }

    private void imagepath(final Activity activity, final String url, final File file, final ImageView ivAddWithHand, final String type) {
        final Dialog dialog = MyDialogUtils.createLoadingDialog(activity, "正在加载...");
        dialog.show();
        OkHttpUtils
                .post()
                .url(Constant.upload)
                .addFile("image", url, file)
                .build()
                .readTimeOut(30000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        dialog.dismiss();
                        Toast.makeText(activity, getString(R.string.error), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        logUtilssss.e("TAG公共图片上传" + response.toString());
                        postReponse(response);
                        dialog.dismiss();
                    }

                    public void postReponse(String json) {
                        imagebenan enterBean = new Gson().fromJson(json, new TypeToken<imagebenan>() {
                        }.getType());
                        if (enterBean.getCode() == 1011) {
                            if (type.equals("1")) {
                                imageurlone = enterBean.getData();
                                Glide.with(activity).load(url).into(ivAddWithHand);
                            } else if (type.equals("2")) {
                                imageurltwo = enterBean.getData();
                                Glide.with(activity).load(url).into(ivAddWithHand);
                            }else if (type.equals("3")) {
                                imageurlthere = enterBean.getData();
                                Glide.with(activity).load(url).into(ivAddWithHand);
                            }
                        } else {
                            Toast.makeText(activity, enterBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }

                    }
                });
    }
}

